package com.zj.core.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import com.zj.core.R
import com.zj.core.adapter.DetailListAdapter
import com.zj.core.base.TitleBarActivity
import com.zj.core.tools.Constant
import com.zj.core.bean.NurseRecResBean
import android.support.v7.widget.LinearLayoutManager
import com.zj.core.tools.Constant.Companion.NURSE_LIST_KEY
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Paint.ANTI_ALIAS_FLAG
import com.dialogutils.ToastUtil
import com.quitutils.SwipeBackLayout
import com.utils.DateUtils
import com.zj.core.base.BaseApplication
import kotlinx.android.synthetic.main.activity_record_detail.*
import java.text.SimpleDateFormat
import java.util.*


open class RecordDetailActivity: TitleBarActivity(),View.OnClickListener{
    private var mRecordBean: NurseRecResBean.DatEntity.RowsEntity? = null
    private var mDetailRecy: DetailListAdapter? = null
    private var mPatternArr: ArrayList<String>? = null
    private var mLayoutManager:LinearLayoutManager?=null
    private var mBundle:Bundle?=null
    private var mDateFormat:SimpleDateFormat?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setQuitMode(SwipeBackLayout.EDGE_LEFT)
    }

    override fun onCreate(groupView: LinearLayout): View? {
        return View.inflate(this, R.layout.activity_record_detail, groupView)
    }

    @SuppressLint("SimpleDateFormat")
    override fun initView(){
        mDateFormat=SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

        setTitleText("详情")
        setRightViewVisible(View.VISIBLE)
        setRightViewText("历史记录")
        setRightViewListener(this)
        change_action_bu.setImageBitmap(textAsBitmap("修改",15f,Color.WHITE))
        change_action_bu.setOnClickListener(this)

        mBundle=Bundle()
        mPatternArr= ArrayList()
        mDetailRecy = DetailListAdapter(this, mPatternArr!!)
        mDetailRecy?.setTextColor(resources.getColor(R.color.colorsGray))

        mRecordBean= intent.getSerializableExtra(Constant.RECORD_DETAIL_KEY) as NurseRecResBean.DatEntity.RowsEntity?
        var msgMeasure=""
        var msgVoice = ""
        var msgStatus=""
        var msgTable=""
        mLayoutManager = LinearLayoutManager(this)
        mLayoutManager?.orientation = LinearLayoutManager.VERTICAL
        detail_title_value.layoutManager = mLayoutManager
        detail_title_value.adapter = mDetailRecy

        mRecordBean?.let {
            nurse_value_view.text=it.nurseid
            partent_value_view.text=it.patientid
            time_value_view.text=it.createtime
            annotation_value_view.text=it.msg

            it.measure?.let {
                if (!mRecordBean!!.measure.equals("")) {
                    msgMeasure = mRecordBean!!.measure.toString()
                }
            }

            it.voice?.let {
                if (!mRecordBean!!.voice.equals("")) {
                    msgVoice = mRecordBean!!.voice.toString()
                }
            }

            it.status?.let {
                if(!mRecordBean!!.status.equals("")){
                    msgStatus= mRecordBean!!.status.toString()
                }
            }

            it.options?.let {
                if(!mRecordBean!!.options.equals("")){
                    msgTable= mRecordBean!!.options.toString()
                }
            }
            formatVoiceData(msgVoice,msgMeasure,msgStatus,msgTable)
        }
    }

    override fun onClick(v: View?){
        super.onClick(v)
        when(v?.id){
            R.id.float_action_bu->{             //进入护士操作记录页面
                mBundle?.putSerializable(NURSE_LIST_KEY,mRecordBean)
                activityJump(this, NurseListActivity().javaClass,mBundle)
            }

            R.id.change_action_bu->{            //修改内容
                val mRecordTime=mDateFormat?.parse(mRecordBean?.systime)
                val mCurrentTime=mDateFormat?.parse(mDateFormat?.format(Date(System.currentTimeMillis())))
                val mInterval=DateUtils.getIntervalDays(mRecordTime,mCurrentTime)
                if(mInterval<1){                //一天内
                    mBundle?.putInt(Constant.DETAIL_ADD_STATUS,1)
                    mBundle?.putSerializable(Constant.DETAIL_ADD_KEY,mRecordBean)
                    activityJumpForResult(
                        BaseApplication.context!!,
                        Constant.REQUEST_RECORD_RES_KEY, RecordActivity().javaClass, mBundle)
                }else{
                    ToastUtil.showShort(BaseApplication.context,"只允许修改当天数据")
                }
            }
        }
    }

    /**
     * 数据修改成功，返回再返回
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode== Constant.RESULT_RECORD_SKY){
            setResult(Constant.RESULT_RECORD_SKY)
            finish()
        }
    }

    /**
     * 修改按钮设置文字
     */
    private fun textAsBitmap(text: String, textSize: Float, textColor: Int): Bitmap?{
        var image: Bitmap?
        Paint(ANTI_ALIAS_FLAG).let {
            it.textSize = textSize
            it.color = textColor
            it.textAlign = Paint.Align.LEFT
            val baseline = -it.ascent()
            val width = (it.measureText(text) + 0.0f).toInt()
            val height = (baseline + it.descent() + 0.0f).toInt()
            image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)

            val canvas = Canvas(image)
            canvas.drawText(text, 0f, baseline, it)
        }
        return image
    }
    /**
     * 格式化历史数据
     *
     * @param voiceStr
     */
    private fun formatVoiceData(voiceStr: String, template: String,status:String,table:String){
        val mValueArr = voiceStr.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        if(status != ""){
            mPatternArr?.add("状态|$status")
        }

        if(table!=""){
            mPatternArr?.add("表单|$table")
        }

        for (mItemValue in mValueArr) {
            var value = ""
            val valueItem = mItemValue.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            if (valueItem.size > 1) {
                value = valueItem[1]
            }
            mPatternArr?.add(valueItem[0] + "|" + value)
        }

        if (template.replace("\n".toRegex(), "") != "") {
            mPatternArr?.add("模板|" + template.replace("\n".toRegex(), ""))
        }
        mDetailRecy?.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        if(mRecordBean!=null){
            mRecordBean=null
        }

        if(mDetailRecy!=null){
            mDetailRecy=null
        }

        if(mPatternArr!=null){
            mPatternArr?.clear()
            mPatternArr=null
        }

        if(mLayoutManager!=null){
            mLayoutManager=null
        }

        if(mBundle!=null){
            mBundle=null
        }
    }
}